import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  loginForm,
  loginResponseData,
  userInfoResponseData
} from '@/api/user/type'
import type { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoutes, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router/index'

import cloneDeep from 'lodash/cloneDeep'

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoutes,
      username: '',
      avatar: '',
      buttons: []
    }
  },
  actions: {
    async userLogin(form: loginForm) {
      const result: loginResponseData = await reqLogin(form)
      const token = result.data

      this.token = token
      SET_TOKEN(token)
    },
    async userInfo() {
      const result: userInfoResponseData = await reqUserInfo()

      this.username = result.data.name
      this.avatar = result.data.avatar
      this.buttons = result.data.buttons

      const userAsyncRoute = filterAsyncRoute(
        cloneDeep(asyncRoute),
        result.data.routes
      )
      this.menuRoutes = [...constantRoutes, ...userAsyncRoute, ...anyRoute]

      ;[...userAsyncRoute, ...anyRoute].forEach((route) => {
        router.addRoute(route)
      })

      return result
    },
    async userLogout() {
      await reqLogout()

      this.token = ''
      this.username = ''
      this.avatar = ''
      REMOVE_TOKEN()
    }
  },
  getters: {}
})

export default useUserStore

function filterAsyncRoute(asyncRoute: any, routes: string[]) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children?.length) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
